﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UnitSoftware.LINQ2SQLExtentions
{
    public class EntityEventSource<TEntity> where TEntity : class
    {
        DataChangeProcessor _processor;

        public event EventHandler<EntityEventArgs<TEntity>> EntityUpdated;
        public event EventHandler<EntityEventArgs<TEntity>> EntityDeleted;
        public event EventHandler<EntityEventArgs<TEntity>> EntityInserted;

        public EntityEventSource(DataChangeProcessor processor)
        {
            _processor = processor;

            processor.EntitiesDeleted += new EventHandler<EntitiesEventArgs>(processor_EntitiesDeleted);
            processor.EntitiesInserted += new EventHandler<EntitiesEventArgs>(processor_EntitiesInserted);
            processor.EntitiesUpdated += new EventHandler<EntitiesEventArgs>(processor_EntitiesUpdated);
        }

        void processor_EntitiesUpdated(object sender, EntitiesEventArgs e)
        {
            if (EntityUpdated == null)
                return;

            foreach (object entity in e.Entities)
                if (entity.GetType() is TEntity)
                    EntityUpdated(this, new EntityEventArgs<TEntity>((TEntity)entity));
        }

        void processor_EntitiesInserted(object sender, EntitiesEventArgs e)
        {
            if (EntityInserted == null)
                return;

            foreach (object entity in e.Entities)
                if (entity.GetType() is TEntity)
                    EntityInserted(this, new EntityEventArgs<TEntity>((TEntity)entity));
        }

        void processor_EntitiesDeleted(object sender, EntitiesEventArgs e)
        {
            if (EntityDeleted == null)
                return;

            foreach (object entity in e.Entities)
                if (entity.GetType() is TEntity)
                    EntityDeleted(this, new EntityEventArgs<TEntity>((TEntity)entity));
        }
    }
}
